const fp = require('lodash/fp')

class Container {
  static of(value) {
    return new Container(value)
  }

  constructor(value) {
    this._value = value
  }

  map(fn) {
    return Container.of(fn(this._value))
  }
}

class Maybe {
  static of(x) {
    return new Maybe(x)
  }

  isNothing() {
    return this._value === null || this._value === undefined
  }

  constructor(x) {
    this._value = x
  }

  map(fn) {
    return this.isNothing() ? this : Maybe.of(fn(this._value))
  }
}

// 练习1
let maybe = Maybe.of([5, 6, 1])

let ex1 = () => {
  return maybe.map((arr) => {
    return fp.map(fp.add(1), arr)
  })._value 
}

console.log(ex1())

// 练习2
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])

let ex2 = () => {
  return xs.map((arr) => {
    return fp.first(arr)
  })._value
}

console.log(ex2())

// 练习3
let safeProp = fp.curry(function(x, o) {
  return Maybe.of(o[x])
})
let user = {id: 2, name: 'Albert'}

let ex3 = () => {
  return safeProp('name')(user).map((name) => {
    return fp.first(name)
  })._value
}

console.log(ex3())

// 练习4
let ex4 = function(n) {
  let m = new Maybe(n)

  return m.map((n) => {
    return parseInt(n)
  })._value
  
}

console.log(ex4(3.4))